package com.helloandroid.activitys.fragments

import android.graphics.Color
import android.view.View
import android.widget.Button
import android.widget.LinearLayout
import android.widget.TextView
import com.business.Analyse
import com.business.AnalyseKey
import com.helloandroid.AppUtil
import com.helloandroid.R
import com.helloandroid.activitys.*
import com.helloandroid.ads.NativeAdUtil
import com.helloandroid.ads.VideoAdUtil
import com.helloandroid.base.BaseFragment
import com.helloandroid.dialogs.MoneyDialog
import com.helloandroid.models.*
import com.helloandroid.tools.MyLog
import com.helloandroid.view.TickTextView
import com.helloandroid.vo.MatchState
import com.helloandroid.vo.TTMatchInfo
import com.helloandroid.vo.UserMatchState
import dai.android.util.AndroidUtils
import java.util.*
import kotlin.Comparator
import kotlin.collections.ArrayList

class MatchFragment1(var matchType: Int, val hbsActivity:TianTianHongBaoActivity):BaseFragment() {
    private val matchData:MatchData = MatchData(ArrayList(), ArrayList())

    lateinit var contentLayout:LinearLayout

    private val lstItemViews = ArrayList<View>()

    override fun getLayoutResId() = R.layout.fragment_match_1

    override fun initView(view: View) {
        contentLayout = findViewById(R.id.contentLayout)
    }

    override fun initData() {
    }

    fun updateUI(newMatchType: Int,data:MatchData){
        MyLog.info("initUI called!")

        matchType = newMatchType
        matchData.matchLst.clear()
        matchData.relatedLst.clear()

        // 赋值
        data.matchLst.forEach {
            matchData.matchLst.add(it)
        }
        data.relatedLst.forEach{
            matchData.relatedLst.add(it)
        }

        // 按照日期进行排序
        // 排序
        // 可以领取的在最前面
        // 剩余的按照顺序来
        // 是否存在未领取的奖励
        Collections.sort(matchData.matchLst,object :Comparator<TTMatchInfo>{
            override fun compare(o1: TTMatchInfo?, o2: TTMatchInfo?): Int {
                if (o1 != null && o2 != null){
                    val o1Getable = o1.isGetable(matchData.relatedLst)
                    val o2Getable = o2.isGetable(matchData.relatedLst)
                    return if(o1Getable == o2Getable){
                        // 两个都领取,或者都没领取. 则按时间顺序来
                        o1.compareTo(o2)
                    }else{
                        // 其中一个领取了
                        if(o1Getable){
                            TTMatchInfo.Negitive
                        }else{
                            TTMatchInfo.Positive
                        }
                    }
                }
                return TTMatchInfo.Negitive
            }
        })


        //===============================
        //  generator to ui
        // 先删除之前的
        contentLayout.removeAllViews()
        lstItemViews.clear()

        if (matchData.matchLst.size < 1){
            return
        }

        // 判断是否参加过
        if (hbsActivity.tthbsData!!.joinCount < 1){
            // 一次没参加过,不显示广告
            // 第一个
            val view = layoutInflater.inflate(R.layout.item_hbmatch,contentLayout,false)
            contentLayout.addView(view)
            lstItemViews.add(view)

            // 插入说明.  helpView不放入 lstItemViews中
            val helpView = layoutInflater.inflate(R.layout.tthbs_item_help,contentLayout,false)
            contentLayout.addView(helpView)
            val tvHelpDesc = helpView.findViewById<TextView>(R.id.tvHelpDesc)
            tvHelpDesc.text = "完成${matchType}步挑战"

            for (i in 1 until matchData.matchLst.size){
                val view = layoutInflater.inflate(R.layout.item_hbmatch,contentLayout,false)
                contentLayout.addView(view)
                lstItemViews.add(view)
            }
        }else{
            // 第一个
            val view1 = layoutInflater.inflate(R.layout.item_hbmatch,contentLayout,false)
            contentLayout.addView(view1)
            lstItemViews.add(view1)

            val view2 = layoutInflater.inflate(R.layout.item_hbmatch,contentLayout,false)
            contentLayout.addView(view2)
            lstItemViews.add(view2)

            // 第3个位置插入广告
            val adView = layoutInflater.inflate(R.layout.tt_native_ad,null,false)
            contentLayout.addView(adView)
            NativeAdUtil.showNativeAd(hbsActivity,adView.findViewById(R.id.nativeView))

            for (i in 2 until matchData.matchLst.size){
                val view = layoutInflater.inflate(R.layout.item_hbmatch,contentLayout,false)
                contentLayout.addView(view)
                lstItemViews.add(view)
            }
        }

        // 进行初始化
        lstItemViews.forEachIndexed { index, view ->
            onUpdateItemView(view,index)
        }
    }

    private fun onUpdateItemView(view: View, position: Int) {
        //
        val tvTitle = view.findViewById<TextView>(R.id.tvTitle)
        val tvFlag = view.findViewById<TextView>(R.id.tvFlag)
        val llCompleted = view.findViewById<LinearLayout>(R.id.llCompleted)
        val btn = view.findViewById<Button>(R.id.btn)
        val tvDesc = view.findViewById<TextView>(R.id.tvDesc)
        val tvTotalMoney = view.findViewById<TextView>(R.id.tvTotalMoney)
        val tvTotalPeople = view.findViewById<TextView>(R.id.tvTotalPeople)
        val tvCompletedPeople = view.findViewById<TickTextView>(R.id.tvCompletedPeople)
        val tvCompletedDesc = view.findViewById<TextView>(R.id.tvCompletedDesc)

        val item = matchData.matchLst[position]
        tvTitle.text = "[${item.title}期]"
        tvTotalMoney.text = "${item.totalMoney}元"
        tvTotalPeople.text = "${item.totalPeople()}"

        // 根据玩家的 参与情况,去更新界面
        val relates = matchData.relatedLst
        val rMatch = relates.find {
            item.matchId == it.matchId
        }
        val bTakePart = ( rMatch != null)

        // case1 未开始
        // case2 进行中
        // case3 已结束
        when(item.matchState){
            MatchState.Unstarted->{
                tvFlag.text = "报名中"
                tvFlag.setTextColor(Color.WHITE)
                tvFlag.setBackgroundResource(R.drawable.dd_hbm_flag_bg_gree)
                llCompleted.visibility = View.GONE
                tvCompletedPeople.tickUpdate = null
                btn.visibility = View.VISIBLE
                tvDesc.text = "报名截止时间23:59:59"
                if (bTakePart){
                    btn.text = "已报名"
                    btn.setBackgroundResource(R.drawable.btn_transparent)
                    btn.setTextColor(resources.getColor(R.color.colorGreen,null))
                    btn.setOnClickListener(null)
                }else{
                    btn.text = "看视频报名"
                    btn.setBackgroundResource(R.drawable.btn_green)
                    btn.setTextColor(Color.WHITE)
                    btn.setOnClickListener {
                        // 报名
                        MyLog.info("点击报名.....")
                        VideoAdUtil.playVideoAd(requireActivity()){success->
                            if (success){
                                takePart(item.matchId)
                            }else{
                                AppUtil.toast("视频广告还未准备好!")
                            }
                        }
                    }
                }
            }
            MatchState.Running->{
                tvFlag.text = "进行中"
                tvFlag.setTextColor(Color.WHITE)
                tvFlag.setBackgroundResource(R.drawable.dd_hbm_flag_bg1)
                llCompleted.visibility = View.VISIBLE
                tvCompletedPeople.text = "${AppUtil.user.bs}"
                tvCompletedDesc.text = "当前步数"
                tvCompletedPeople.tickUpdate = {
                    tvCompletedPeople.text = "${AppUtil.user.bs}"
                }
                tvCompletedPeople.setTextColor(resources.getColor(R.color.dd_main_blue,null))
                btn.visibility = View.VISIBLE
                btn.setBackgroundResource(R.drawable.btn_transparent)
                tvDesc.text = "活动结束时间:今日23:59:59"
                btn.setTextColor(Color.BLACK)
                btn.setOnClickListener(null)
                if(bTakePart){
                    btn.text = "已报名"
                }else{
                    btn.text = "未报名"
                }
            }
            MatchState.Ended->{
                tvFlag.text = "已结束"
                tvFlag.setTextColor(Color.GRAY)
                tvFlag.setBackgroundResource(R.drawable.dd_hbm_flag_bg2)
                llCompleted.visibility = View.VISIBLE
                tvCompletedPeople.text = "${item.totalCompletedPeople()}"
                tvCompletedPeople.tickUpdate = null
                tvCompletedPeople.setTextColor(resources.getColor(R.color.colorGreen,null))
                tvCompletedDesc.text = "完成目标人数"
                if(bTakePart){
                    btn.visibility = View.VISIBLE
                    when(rMatch!!.state){
                        UserMatchState.Geted->{
                            btn.text = "已领取"
                            btn.setBackgroundResource(R.drawable.dd_btn_gray)
                            btn.setTextColor(Color.WHITE)
                            tvDesc.text = "您已经领取奖励"
                            btn.setOnClickListener(null)
                        }
                        UserMatchState.Completed->{
                            btn.text = "领取"
                            btn.setBackgroundResource(R.drawable.btn_red)
                            btn.setTextColor(Color.WHITE)
                            tvDesc.text = "您可以领取奖励"
                            btn.setOnClickListener{
                                MyLog.info("点击领奖...")
                                btnAwardClicked(item)
                            }
                        }
                        UserMatchState.UnComplete->{
                            btn.text = "未完成"
                            btn.setBackgroundResource(R.drawable.dd_btn_gray)
                            tvDesc.text = "很遗憾,您未完成比赛"
                            btn.setOnClickListener(null)
                        }
                        else -> MyLog.elog("Unreached!")
                    }
                }else{
                    btn.visibility = View.INVISIBLE
                    tvDesc.text = "您未报名此次活动"
                    btn.setOnClickListener(null)
                }
            }
        }
    }

    private fun takePart(matchId:Int){
        hbsActivity.model.tthbsTakePart(matchId){success,newPeople,newRobot,newRobotsOKRate->
            if (success){
                AppUtil.toast("报名成功!")
                // 先更新数据,再更新UI
                val ttData = hbsActivity.tthbsData!!
                ttData.joinCount += 1
                if(matchType == TTMatchInfo.M3000){
                    val matchInfo = ttData.m3.matchLst.find { it.matchId == matchId }
                    val info = matchInfo!!
                    info.people = newPeople
                    info.robots = newRobot
                    info.robotsOKRate = newRobotsOKRate
                    info.totalMoney = ((newPeople + info.robots) * ttData.m3Ratio * 100).toInt() / 100f
                    ttData.m3.relatedLst.add(RelatedMatch(matchId,UserMatchState.TakePart))
                    // 更新UI
                    updateUI(matchType,ttData.m3)
                }else{
                    val matchInfo = ttData.m8.matchLst.find { it.matchId == matchId }
                    val info = matchInfo!!
                    info.people = newPeople
                    info.totalMoney = ((newPeople + info.robots) * ttData.m8Ratio * 100).toInt() / 100f
                    ttData.m8.relatedLst.add(RelatedMatch(matchId,UserMatchState.TakePart))
                    updateUI(matchType,ttData.m8)
                }
            }else{
                AppUtil.toast("报名失败!")
            }
        }
    }

    private fun btnAwardClicked(item:TTMatchInfo){

        if (AppUtil.serverConfig.tthbsRewardVideo > 0){
            // 需要看视频
            VideoAdUtil.playVideoAd(requireActivity()){videoSuccess->
                if (videoSuccess){
                    Analyse.report(AnalyseKey.TTHBS_VideoAward)
                    realAward(item.matchId)
                }else{
                    AppUtil.toast("视频还未准备好!")
                }
            }
        }else{
            // 不需要看视频
            // 弹出奖励红包, 还要刷新界面
            Analyse.report(AnalyseKey.TTHBS_Award)
            realAward(item.matchId)
        }
    }

    private fun realAward(matchId:Int){
        hbsActivity.model.award(matchId){success,addedMoney->
            if (success){
                // 比赛信息的状态也会发生改变
                val matchData = hbsActivity.getMatchData(matchType)
                val relatedInfo = matchData.relatedLst.find { it.matchId == matchId }
                relatedInfo!!.state = UserMatchState.Geted

                // 弹出奖励红包, 还要刷新界面
                MoneyDialog(requireActivity(),addedMoney).show()
                updateUI(matchType,hbsActivity.getMatchData(matchType))
            }else{
                AppUtil.toast("领取奖励失败!")
            }
        }
    }

    fun takePartMatch(){
        if (!AndroidUtils.networkConnected(AppUtil.app)){
            AppUtil.toast("请打开网络!")
            return
        }

        if (matchData.matchLst.size < 1){
            AppUtil.toast("没有比赛赛事!")
            return
        }
        val item = matchData.matchLst[0]
        takePart(item.matchId)
    }


}